package com.eco.fanliapp.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.entity.NoticeAccount;
import com.eco.fanliapp.entity.TaobaoScheme;
import com.eco.fanliapp.service.INoticeAccountService;
import com.eco.fanliapp.service.ISmsService;
import com.eco.fanliapp.service.TaoBaoPlanService;
import com.eco.fanliapp.utils.MessageUtils;
import org.apache.commons.collections.CollectionUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * 联盟到期通知
 * @author zhuchao
 * @date 2019-09-23
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class TaskAcountJob implements Job {

    private static final Logger logger = LoggerFactory.getLogger(TaskAcountJob.class);
    @Autowired
    private TaoBaoPlanService taoBaoPlanService;
    @Autowired
    private INoticeAccountService noticeAccountService;
    @Autowired
    private ISmsService smsService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap =  jobDetail.getJobDataMap();
        String dataMapKey = "runCount";
        int executeCount = 0;
        if (dataMap.containsKey(dataMapKey)) {
            executeCount = dataMap.getInt(dataMapKey);
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        logger.info("***************************************开始执行定时任务-联盟到期通知-TaskAcountJob：executeCount="+executeCount+"--startTime="+startTime);

        try {
            logger.info("--->  运行中[" + new Date() + "]");
            int count = 0;
            List<TaobaoScheme> taoBaoPlanList = taoBaoPlanService.findTaoBaoPlanAll(null);
            StringBuffer str = new StringBuffer();
            for (TaobaoScheme taoBaoPlan: taoBaoPlanList) {
                //到期时间
                long upTime = taoBaoPlan.getExpireTime().getTime();
                //获取剩余时间
                long time = upTime - System.currentTimeMillis();
                if ( time/(24*3600*1000) <= 3){
                    //该步即不会第一位有逗号，也防止最后一位拼接逗号！
                    if (str.length() > 0) {
                        str.append(",");
                    }
                    str.append(taoBaoPlan.getTaobaoName());
                    count ++;
                }
            }

            //如果存在即将过期联盟
            if(count > 0){
                //组装消息内容（联盟 + 个数 + 通知）
                //String content = str.toString() + count + "个联盟即将到期！";
                String content = str.toString() + count;

                //获取通知账户
                QueryWrapper<NoticeAccount> queryWrapper = new QueryWrapper<>();
                //联盟到期
                queryWrapper.eq("type",0);
                queryWrapper.eq("enable",1);
                queryWrapper.eq("deleted",0);
                List<NoticeAccount> list = noticeAccountService.list(queryWrapper);
                if(CollectionUtils.isNotEmpty(list)){
                    StringBuffer str1 = new StringBuffer();
                    for(NoticeAccount account:list){
                        if(str1.length() > 0){
                            str1.append(",");
                        }
                        str1.append(account.getPhone());
                    }
                    String phone = str1.toString();
                    logger.info("通知电话{}，即将到期联盟{}",phone,content);
                    //短信发送
                    //String result = MessageUtils.sendMesage(phone, content);
                    String result = smsService.sendSms4(phone,content);
                    logger.info("短信发送结果{}",result);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("联盟到期通知错误");
        }

        long endTime = System.currentTimeMillis();
        logger.info("***************************************结束执行定时任务-联盟到期通知-TaskAcountJob：executeCount="+executeCount+"--endTime="+endTime+"--耗时="+(endTime-startTime));

    }
}
